﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chemistry.Tools
{
    using System.Configuration;
    using System.Net.Http;
    using System.Net.Http.Headers;

    /// <summary>
    /// 题库Http
    /// 用于获取题目
    /// </summary>
    public sealed class HttpBaseQuestion
    {
        private static HttpClient client;

        private HttpBaseQuestion() { }

        static HttpBaseQuestion()
        {
            client = new HttpClient();
            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["QuestionAddress"]);
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
        }

        private static HttpClient GetHttpBase()
        {
            if (client == null || client.BaseAddress == null)
            {
                client.BaseAddress = new Uri(ConfigurationManager.AppSettings["QuestionAddress"]);
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
            }
            return client;
        }

        /// <summary>
        /// 异步Get请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<T> GetAsync<T>(string url) where T : class
        {
            HttpResponseMessage response =await client.GetAsync(url);  // Blocking call（阻塞调用）! 
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsAsync<T>();
                return data;
            }
            else
            {
                LogTool.WriteErrorLog(string.Format("异步Get请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        public static async Task<T> PostAsJsonAsync<T>(string url, object entity) where T : class
        {
            HttpResponseMessage response = await client.PostAsJsonAsync(url, entity);
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsAsync<T>();
                return data;
            }
            else
            {
                LogTool.WriteErrorLog(string.Format("异步Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }
    }
}
